//
// Created by andy on 18-8-21.
//
#include <iostream>
#include <sstream>
#include <netinet/in.h>
#include <netdb.h>
#include <cstring>
#include <zconf.h>
#include "HttpConnect.h"

using namespace std;


HttpConnect::HttpConnect() {
}

HttpConnect::~HttpConnect() {
}

void HttpConnect::socketHttp(std::string host, std::string request) {
    int sockfd;
    struct sockaddr_in address;
    struct hostent *server;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    address.sin_family = AF_INET;
    address.sin_port = htons(80);
    server = gethostbyname(host.c_str());
    if (server == NULL) {
        printf("gethostbyname failed, please check the network");
        return;
    }

    memcpy((char *) &address.sin_addr.s_addr, (char *) server->h_addr, server->h_length);
    if (-1 == connect(sockfd, (struct sockaddr *) &address, sizeof(address))) {
        return;
    }

    write(sockfd, request.c_str(), request.size());
    char buf[1024 * 1024] = {0};
    int offset = 0;
    int rc;

    while (rc = read(sockfd, buf + offset, 1024)) {
        offset += rc;
    }

    close(sockfd);
    printf("result: \n%s\n" ,buf);
    buf[offset] = 0;
}

void HttpConnect::postData(std::string host, std::string path, std::string cardNo, std::string datetime) {
    //POST请求方式
    int total_len =  strlen("number=") + strlen(cardNo.c_str()) + strlen("&datetime=") + strlen(datetime.c_str());
    std::stringstream stream;
    stream << "POST " << path;
    stream << " HTTP/1.1\r\n";
    stream << "Host: " << host << "\r\n";
    stream << "Content-Type: application/x-www-form-urlencoded\r\n";
    stream << "Cache-Control: no-cache\r\n";
    stream << "Content-Length:" << total_len << "\r\n\r\n";
    stream << "number=" << cardNo << "&datetime=" << datetime;

    socketHttp(host, stream.str());
}

//void HttpConnect::getData(std::string host, std::string path, std::string get_content) {
//    //GET请求方式
//    std::stringstream stream;
//    stream << "GET " << path << "?" << get_content;
//    stream << " HTTP/1.0\r\n";
//    stream << "Host: " << host << "\r\n";
//    stream
//            << "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3\r\n";
//    stream << "Connection:close\r\n\r\n";
//    socketHttp(host, stream.str());
//}
